package com.prince.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.entity.UserName;
import com.prince.mapper.UserMapper;
import com.prince.mapper.x.UserLimitsMapper;
import com.prince.model.Config;
import com.prince.model.User;
import com.prince.model.UserExample;
import com.prince.model.UserExample.Criteria;
import com.prince.page.Page;
import com.prince.util.*;
import com.prince.web.base.BaseService;
import com.prince.web.base.SessionUtil;
import com.prince.web.service.ConfigService;
import com.prince.web.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户
 * 
 * @author WangPeixi
 *
 */
@Service
public  class UserServiceImpl extends BaseService implements UserService {

	@Resource
	private UserMapper userMapper; // 用户

	@Resource
	private UserLimitsMapper userLimitsMapper; // 用户查询菜单

	@Resource
	private ConfigService confingService; // 常量字典



	/* 根据用户id查询用户
	 * @see com.prince.service.back.service.UserService#getUserById(com.prince.model.User)
	 */
	@Override
	public Map<String, Object> getUserById(User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		User u = userMapper.selectByPrimaryKey(user.getId());
		List<User> list = new ArrayList<>();
		list.add(u);

		response.put("list", list);
		return response.toHashMap();
	}

	/*
	 * 分页查询所有用户
	 * 
	 * @see com.prince.service.back.service.UserService#findUserByPage(java.util.Map,
	 * com.prince.page.Page)
	 */
	@Override
	public Map<String, Object> findUserByPage(Map<String, Object> params, Page page) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("UserServiceImpl findUserByPage 分页查询用户");
		if (null == params || params.size() == 0) {
			logger.debug("用户请求参数为空");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//获取session 中的对象 
		if(null == params.get("user")) {
			logger.debug("登录用户为空");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		
		UserExample userExample = new UserExample();
		Criteria createCriteria = userExample.createCriteria();
		
		
		User u = (User) params.get("user");
		if(!StringUtil.stringEquals(Constants.ADMIN,u.getBelongType())) {
			if(null !=u.getParentId() && Constants.ZERO != u.getParentId()) {
				//员工查上级id   管理员查自己id
				if(StringUtil.stringEquals(Constants.STAFF, u.getBelongType())){
					createCriteria.andParentIdEqualTo(u.getParentId());
				}else {
					createCriteria.andParentIdEqualTo(u.getId());
				}
			}
		}
		
		
		// 用户名 loginName=, belongType=, departmentId=, status=
		if (MapUtil.isNotEmpty(params, "linkman")) {
			createCriteria.andLinkmanLike("%" + params.get("linkman").toString() + "%");
		}
		// 手机号
		if (MapUtil.isNotEmpty(params, "phone")) {
			createCriteria.andPhoneLike("%" + params.get("phone").toString() + "%");
		}
		// 用户类型
		if (MapUtil.isNotEmpty(params, "belongType")) {
			createCriteria.andBelongTypeEqualTo(params.get("belongType").toString());
		}
		//角色
		if (MapUtil.isNotEmpty(params, "roleId")) {
			createCriteria.andRoleIdEqualTo(Integer.parseInt(params.get("roleId").toString()));
		}
		// 状态
		if (MapUtil.isNotEmpty(params, "status")) {
			createCriteria.andStatusEqualTo(params.get("status").toString());
		}


		// 昵称
		if (MapUtil.isNotEmpty(params, "loginName")) {
			createCriteria.andLoginNameEqualTo(params.get("loginName").toString());
		}

		if (MapUtil.isNotEmpty(params, "startTime")) {
			Date startTime = DateUtil.strToDate(params.get("startTime").toString(), "yyyy-MM-dd hh:mm:ss");
			Date endTime = DateUtil.strToDate(params.get("endTime").toString(), "yyyy-MM-dd hh:mm:ss");
			createCriteria.andCreatedBetween(startTime, endTime);
		}
		int total = userMapper.countByExample(userExample);

		if (null != page) {
			userExample.setPage(page);
		}

		userExample.setOrderByClause("created desc");
		List<User> list = userMapper.selectByExample(userExample);
		return response.toHashMapByPage(total, list);
	}

	/*
	 * 添加用户
	 * 
	 * @see com.prince.service.back.service.UserService#addUser(com.prince.model.User)
	 */
	@Override
	public synchronized Map<String, Object> addUser(User user, User u) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();

		// 重名判断
		UserExample userExample = new UserExample();
		Criteria createCriteria = userExample.createCriteria();
		if (StringUtil.isNotEmpty(user.getLinkman())) {
			createCriteria.andLinkmanEqualTo(user.getLinkman());
		}
		List<User> selectByExample = userMapper.selectByExample(userExample);
		if (!selectByExample.isEmpty()) {
			logger.info("UserServiceImpl addUser 添加用户");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
		}

		// 判断手机号
		if (StringUtil.isNotEmpty(user.getPhone())) {
			userExample.clear();
			userExample.createCriteria().andPhoneEqualTo(user.getPhone());
			List<User> userList = userMapper.selectByExample(userExample);
			if (ListUtils.isNotEmpty(userList)) {
				logger.info("UserServiceImpl addUser 添加用户");
				return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.repeatPhone).toHashMap();
			}
		}
		
		//补充数据
		user.setCreated(new Date());
		
		// 父id   session中belongType  员工添加父id  不是员工添加自己的id
		Integer id = u.getId();
		if(StringUtil.stringEquals(Constants.STAFF, u.getBelongType())) {
			id=u.getParentId();
		}
		user.setParentId(id);
		if (user.getPwd() != null && user.getPwd().length() > 0) {
			user.setPwd(MD5Util.encryptByMd5AndBASE64(user.getPwd()));
		}
		// 状态为空 直接禁用
		if (StringUtil.isEmpty(user.getStatus())) {
			user.setStatus(Constants.DISABLE);
		}

		int i = userMapper.insertSelective(user);
		if (!(i > 0)) {
			logger.info("UserServiceImpl addUser 添加用户");
			logger.debug("添加用户失败", JSON.toJSONString(user));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//添加一次用户从新加入一次redis
		return response.toHashMap();
	}

	/*
	 * 删除用户
	 * 
	 * @see com.prince.service.back.service.UserService#delUser(com.prince.model.User)
	 */
	@Override
	public Map<String, Object> delUser(User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		int i = userMapper.deleteByPrimaryKey(user.getId());
		if (!(i > 0)) {
			logger.info("UserServiceImpl delUser 删除用户失败");
			logger.debug("删除失败!", JSON.toJSONString(user));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		return response.toHashMap();
	}

	/*
	 * 更新用户
	 * 
	 * @see com.prince.service.back.service.UserService#updateUser(com.prince.model.User)
	 */
	@Override
	public Map<String, Object> updateUser(User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();

		// 判断重名
		UserExample userExample = new UserExample();
		if (StringUtil.isNotEmpty(user.getLinkman()) && StringUtil.isNotEmpty(user.getRemark())
				&& !user.getLinkman().equals(user.getRemark())) {
			Criteria createCriteria = userExample.createCriteria();
			createCriteria.andLinkmanEqualTo(user.getLinkman());
			List<User> list = userMapper.selectByExample(userExample);
			if (!list.isEmpty()) {
				logger.info("UserServiceImpl updateUser 更新用户失败");
				return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
			}
		}

		// 判断手机号described
		if (StringUtil.isNotEmpty(user.getPhone())) {
			if (!StringUtil.stringEquals(user.getPhone(), user.getDescribed())) {
				userExample.clear();
				userExample.createCriteria().andPhoneEqualTo(user.getPhone());
				List<User> userList = userMapper.selectByExample(userExample);
				if (ListUtils.isNotEmpty(userList)) {
					logger.info("UserServiceImpl addUser 添加用户");
					return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.repeatPhone).toHashMap();
				}
			}
		}

		// user.setRemark(null);
		if (Constants.FROZEN.equals(user.getStatus())) {
			user.setLastLoginFailTime(null);
		}
		if (null == user.getRoleId()) {
			user.setRoleId(Constants.ZERO);
		}
		User u = userMapper.selectByPrimaryKey(user.getId());
		if (!u.getPwd().equals(user.getPwd())) {
			user.setPwd(MD5Util.encryptByMd5AndBASE64(user.getPwd()));
		}
		user.setRemark(""); // 将备注设置为空
		int i = userMapper.updateByPrimaryKeySelective(user);
		if (!(i > 0)) {
			logger.info("UserServiceImpl updateUser 更新用户失败");
			logger.debug("更新失败!", JSON.toJSONString(user));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		return response.toHashMap();
	}

	/*
	 * 用户登录
	 * 
	 * @see com.prince.service.UserService#login(com.prince.model.User)
	 */
	@Override
	@Transactional
	public Map<String, Object> login(User user,String requestURL) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		user.setPwd(MD5Util.encryptByMd5AndBASE64(user.getPwd()));
		UserExample userExample = new UserExample();
		// 添加查询条件 loginName
		Criteria criteria = userExample.createCriteria();
		criteria.andLinkmanEqualTo(user.getLinkman());
		List<User> list = userMapper.selectByExample(userExample);

		// 没数据
		if (list == null || list.size() == 0) {
			logger.debug("UserServiceImpl login 用户名不存在!");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.loginFail).toHashMap();
		}
		User u = list.get(0);

		// 用户状态
		if (Constants.DISABLE.equals(u.getStatus()) || StringUtil.isEmpty(u.getStatus())) {
			logger.debug("UserServiceImpl login 账户已停用!");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.userDeactivated).toHashMap();
		}

		// 查询常量
//		Config loginfreezeFailtime = confingService.findConfigName(Constants.LOGINFREEZEFAILTIME);
//		Integer time = Integer.parseInt(loginfreezeFailtime.getValue()); // 2小时内
//		Config loginFailNumber = confingService.findConfigName(Constants.LOGINFAILNUMBER);
//		Integer sum = Integer.parseInt(loginFailNumber.getValue()); // 失败次数

		// 冻结状态
//		if (u.getStatus().equals(Constants.FROZEN)) {
//			// 判断登录时间
//			if (null != u.getLastLoginFailTime()) {
//				// 小于2小时 并且 大于失败次数
//				if (DateUtil.getBetween(new Date(), u.getLastLoginFailTime()) < time) {
//					if (u.getLoginFail() > sum) {
//						logger.debug("UserServiceImpl login 账户已冻结！");
//						return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.userFreezeTime).toHashMap();
//					} else {
//						logger.debug("UserServiceImpl login 账户已冻结！");
//						return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.userFreeze).toHashMap();
//					}
//
//				}
//			} else {
//				logger.debug("UserServiceImpl login 账户已冻结！");
//				return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.userFreeze).toHashMap();
//			}
//
//		}

		// 判断密码 63ee451939ed580ef3c4b6f0109d1fd0 4297f44b13955235245b2497399d7a93
		if (!StringUtil.stringEquals(user.getPwd(), u.getPwd())) {// efe6398127928f1b2e9ef3207fb82663
			logger.debug("UserServiceImpl login 用户名或密码错误!" + u.getLoginFail());
//			u.setLoginFail(u.getLoginFail() + 1);
//			u.setLastLoginFailTime(new Date());
//			if (u.getLoginFail() >= sum) {
//				u.setStatus(Constants.FROZEN);
//			}
//			userMapper.updateByPrimaryKey(u);
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.loginFail).toHashMap();
		}

		if (null== u.getRoleId() || Constants.ZERO.equals(u.getRoleId())) {
			logger.debug("UserServiceImpl login 用户没有角色权限");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.notRole).toHashMap();
		}

		// 更新最后一次登录的ip、时间、失败次数、状态
		u.setLastLoginIp(user.getLastLoginIp());
		u.setLastLoginTime(new Date());
		u.setLoginFail(Constants.ZERO);
		u.setStatus(Constants.ENABLE);
		userMapper.updateByPrimaryKeySelective(u);
		//将User加入session中
		SessionUtil.setSession(u);
		return response.toHashMap();
	}

	/**
	 * 根据条件查询用户
	 */
	@Override
	public List<User> findUserByCondition(User user) {
		UserExample userExample = new UserExample();
		Criteria criteria = userExample.createCriteria();
		if (StringUtil.isNotEmpty(user.getBelongType())) {
			criteria.andBelongTypeEqualTo(user.getBelongType());
		}
		if (StringUtil.isNotEmpty(user.getLoginName())) {
			criteria.andLoginNameEqualTo(user.getLoginName());
		}
		if (!StringUtil.isEmpty(user.getPhone())) {
			criteria.andPhoneEqualTo(user.getPhone());
		}
		List<User> list = userMapper.selectByExample(userExample);

		if (null == list || list.size() == 0) {
			logger.debug("UserServiceImpl [findUserByCondition] find agentList is null");
			return null;
		}
		return list;
	}


	/*
	 * 修改密码
	 * 
	 * @see com.prince.service.back.service.UserService#updatePwd(com.prince.model.User)
	 */
	@Override
	public Map<String, Object> updatePwd(User user, User u) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		String pwd=user.getRemark();
		user.setPwd(MD5Util.encryptByMd5AndBASE64(user.getPwd()));
		User us = userMapper.selectByPrimaryKey(u.getId());
		// 先判断旧密码是否正确
		logger.info("旧密码 ： " + user.getPwd() + "    新密码：" + us.getPwd());
		if (!StringUtil.stringEquals(us.getPwd(), user.getPwd())) {
			logger.debug("UserServiceImpl updatePwd 原始密码错误！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.oldPwd).toHashMap();
		}
		String regex="^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
		if(!pwd.matches(regex)) {
			logger.debug("UserServiceImpl updatePwd 新密码格式错误！");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.matchPwd).toHashMap();
		}
		user.setRemark(MD5Util.encryptByMd5AndBASE64(user.getRemark()));
		// 判断新密码是否一样 不一样更新
		logger.info("旧密码 ： " + user.getPwd() + "    新密码：" + user.getRemark());
		if (!StringUtil.stringEquals(user.getPwd(), user.getRemark())) {
			us.setPwd(user.getRemark());
			int i = userMapper.updateByPrimaryKeySelective(us);
			if (!(i > 0)) {
				logger.debug("修改密码失败");
			} else {
				logger.debug("修改密码成功");
			}
		}
		logger.info("修改登录密码返回：" + response.toHashMap());
		return response.toHashMap();
	}


	/*
	 * 异常登录查询
	 * 
	 * @see
	 * com.prince.service.back.service.UserService#findloginAbnormal(java.lang.String)
	 */
	@Override
	public String findloginAbnormal(String loginabnormal) {
		if (null == loginabnormal) {
			return Constants.NO;
		}
		Config findConfigName = confingService.findConfigName(loginabnormal);
		return null != findConfigName ? findConfigName.getValue() :Constants.NO;
	}

	@Override
	public String findLonginTime(String loginTime) {
		if (null == loginTime) {
			return Constants.NO;
		}
		Config findConfigName = confingService.findConfigName(loginTime);
		return null != findConfigName ? findConfigName.getValue() :Constants.NO;
	}

	/* 
	 * 查询用户昵称
	 * @see com.prince.service.UserService#findUserName(com.prince.model.User)
	 */
	@Override
	public Map<String, Object> findParentUserName(User u) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		Map<String,Object> map = new HashMap<String, Object>();
		if(StringUtil.stringNotEquals(Constants.ADMIN, u.getBelongType())) {
			if(StringUtil.stringEquals(Constants.STAFF, u.getBelongType())) {
				map.put("id", u.getId());
			}else {
				map.put("parentId", u.getId());
			}
		}
		
		List<UserName> list = userLimitsMapper.findParentUserName(map);
		response.put("data", list);
		return response.toHashMap();
	}


}
